<?php

namespace app\common\traits;

use app\admin\model\GroupAuth;
use app\common\enum\Status;
use app\common\model\Company;
use app\common\model\CompanyWarehouse;
use app\common\model\Dealer;
use app\common\model\DealerGoods;
use app\common\model\DealerGoods as DealerGoodsModel;
use app\common\model\DealerGoodsCate;
use app\common\model\DealerGoodsSpec;
use app\common\model\Driver;
use app\common\model\Goods;
use app\common\model\GoodsBrand;
use app\common\model\GoodsCate;
use app\common\model\GoodsUnit;
use app\common\model\Group;
use app\common\model\Region1;
use app\common\model\Salesman;
use app\common\model\Store;
use app\common\model\Supplier;
use app\common\service\annotation\NodeAnnotation;
use app\common\service\AuthService;
use app\common\service\CategoryService;
use app\company\model\CompanyAuth;
use app\company\model\CompanyWarehouseGoods;
use app\company\model\DealerStore;
use think\db\Query;
use think\response\Json;

trait SearchTrait
{
    use RegionTrait;
    /**
     * @NodeAnnotation(title="集团查询组件")
     */
    public function groupList($groupId = 0): Json
    {
        $sql = $this->model = new Group();
        // 指定字段
        if ($this->fields) $sql = $sql->field($this->fields);
        // 单条查询
        if ($groupId) {
            return $this->success($sql->find((int)$groupId));
        }
        // 指定排序 (控制器可修改覆盖继承的排序）
        $sql = $sql->order($this->sort);
        // 查询条件
        [, $where] = $this->buildSearchParams();
        if ($where) $sql = $sql->where($where);
        // 指定分页
        if (!empty($this->get['page']) && !empty($this->get['limit'])) {
            $list = $sql->paginate($this->get['limit']);
        } else {
            $list = $sql->select();
        }
        return $this->success($list);
    }

    /**
     * @NodeAnnotation(title="公司查询组件")
     */
    public function companyList($companyId = 0)
    {
        $sql = $this->model = new Company();
        // 指定字段
        if ($this->fields) $sql = $sql->field($this->fields);
        // 单条查询
        if ($companyId) {
            return $this->success($sql->find((int)$companyId));
        }
        // 指定排序 (控制器可修改覆盖继承的排序）
        $sql = $sql->order($this->sort);
        // 查询条件
        [, $where] = $this->buildSearchParams();
        if ($where) $sql = $sql->where($where);
        // 指定分页
        if (!empty($this->get['page']) && !empty($this->get['limit'])) {
            $list = $sql->paginate($this->get['limit']);
        } else {
            $list = $sql->select();
        }
        return $this->success($list);
    }

    /**
     * @NodeAnnotation(title="授权列表")
     * 有空做一下缓存
     */
    public function authList($authId = null): Json
    {
        $id = $this->appName == 'admin' ? $this->groupId : $this->companyId;
        // 获取当前管理员角色ID
        $authService = app(AuthService::class, ['uid' => $this->uid, 'app_name' => $this->appName]);
        $list        = $authService->getAuthMenuList($id, $authId);
        return $this->success($list);
    }

    public function roleList(): Json
    {
        $sql  = $this->model = $this->appName == 'admin' ? new GroupAuth() : new CompanyAuth();
        $list = $sql->field('id,title')->where('status', Status::NORMAL)->select();
        return $this->success($list);
    }

    /**
     * @NodeAnnotation(title="分类查询组件")
     * 有空做一下缓存
     */
    public function cateList(): Json
    {
        $sql  = new GoodsCate();
        $list = $sql->field('id,pid,name')->where('status', Status::NORMAL)->select();
        return $this->success((new CategoryService())->getTreeData($list));
    }

    /**
     * @NodeAnnotation(title="品牌查询组件")
     */
    public function brandList(): Json
    {
        $sql  = new GoodsBrand();
        $list = $sql->field('id,name')->where('status', Status::NORMAL)->select();
        return $this->success($list);
    }

    /**
     * @NodeAnnotation(title="单位查询组件")
     */
    public function unitList(): Json
    {
        $sql  = $this->model = new GoodsUnit();
        $list = $sql->field('id,name')->where('status', Status::NORMAL)->select();
        return $this->success($list);
    }

    /**
     * @NodeAnnotation(title="经销商查询组件")
     */
    public function dealerList(): Json
    {
        $sql = $this->model = new Dealer();
        [, $where] = $this->buildSearchParams();
        if (!empty($this->companyId)) $where['company_id'] = $this->companyId;
        if ($this->fields) $sql = $sql->field($this->fields);
        $list = $sql->where($where)->order($this->sort)->select();
        return $this->success($list);
    }

    /**
     * @NodeAnnotation(title="供应商查询组件")
     */
    public function supplierList(): Json
    {
        $sql = $this->model = new Supplier();
        [, $where] = $this->buildSearchParams();
        if (!empty($this->companyId)) $sql = $sql->where('company_id', $this->companyId);
        if ($this->fields) $sql = $sql->field($this->fields);
        $list = $sql->where($where)->order($this->sort)->select();
        return $this->success($list);
    }

    /**
     * @NodeAnnotation(title="门店列表")
     */
    public function storeList(): Json
    {
        $sql = $this->model = new Store();
        [, $where] = $this->buildSearchParams();
        $get = $this->get;
        foreach ($where as $k => $v) {
            if (str_contains($v[0], 'salesman_id')) {
                $sql = $sql->hasWhere('salesman', function ($query) use ($v)
                {
                    $query->where($v[0], $v[1], $v[2]);
                });
                unset($where[$k]);
            }
            if (str_contains($v[0], 'dealer_id')) {
                $storeIds = DealerStore::where('dealer_id', $v[2])->column('store_id');
                $sql      = $sql->where('id', 'in', $storeIds);
                unset($where);
            }
        }
        $sql = $sql->where('status', 1)->order($this->sort);
        if (!empty($where)) $sql = $sql->where($where);
        if (!empty($this->companyId)) $sql = $sql->where('company_id', $this->companyId);
        if (!empty($get['limit'])) {
            $list = $sql->paginate($get['limit']);
        } else {
            $list = $sql->select();
        }
        $list->each(function ($vo)
        {
            $vo->region = $vo->region()->field('id,name')->find();
        });
        return $this->success($list);
    }

    /**
     * @NodeAnnotation(title="区域列表")
     */
    public function regionList(): Json
    {
        $sql = $this->model = new Region1();
        [, $where] = $this->buildSearchParams();
        $where[] = ['company_id', '=', $this->companyId];
        if ($this->fields) $sql = $sql->field($this->fields);
        $list = $sql->where($where)->order($this->sort)->select();
        return $this->success($list);
    }

    /**
     * @NodeAnnotation(title="司机列表")
     */
    public function driverList(): Json
    {
        $sql = $this->model = new Driver();
        [, $where] = $this->buildSearchParams();
        $where[] = $this->defaultWhere[0];
        if ($this->fields) $sql = $sql->field($this->fields);
        $list = $sql->where($where)->order($this->sort)->select();
        return $this->success($list);
    }

    /**
     * @NodeAnnotation(title="商品列表")
     */
    public function goodsList(): Json
    {
        $sql = $this->model = new Goods();
        [$limit, $where] = $this->buildSearchParams();
        $sql = $sql->where($where)->order(['sort' => 'desc', 'id' => 'desc']);
        if (!empty($this->get['limit'])) {
            $list = $sql->paginate($limit);
        } else {
            $list = $sql->select();
        }
        $list->each(function ($vo)
        {
            $vo->brand = $vo->brand()->field('id,name')->find();
            $vo->cate  = $vo->cate()->field('id,name')->find();
            $vo->spec  = $vo->spec()->select();
        });
        return $this->success($list);
    }

    /**
     * @NodeAnnotation(title="经销商商品列表")
     */
    public function dealerGoodsList(): Json
    {
        $sql = $this->model = new DealerGoods();
        [, $where] = $this->buildSearchParams();
        $get = $this->request->get();
        if (empty($get['limit'])) {
            $list = $sql->where($where)->where('status', 1)->with('spec')->select();
        } else {
            $list = $sql->where($where)->where('status', 1)->with('spec')->paginate($get['limit']);
        }
        $list = $list->each(function ($goods)
        {
            $goods->spec->each(function ($spec) use ($goods)
            {
                $stock = 0;
                if ($spec->ratio != 0) $stock = bcdiv($goods->sales_stock, $spec->ratio);
                $spec->stock = $stock;
            });
        });
        return $this->success($list);
    }

    /**
     * @NodeAnnotation(title="经销商商品规格列表")
     */
    public function dealerGoodsSpecList(): Json
    {
        $sql = $this->model = new DealerGoodsSpec();
        [$limit, $where] = $this->buildSearchParams();
        //        foreach ($where as $k => $v) {
        //            if (str_contains($v[0], 'cate_id')) {
        //                $sql = $sql->hasWhere('goods', function ($query) use ($v)
        //                {
        //                    $query->where($v[0], $v[1], $v[2]);
        //                });
        //                unset($where[$k]);
        //            }
        //            if (str_contains($v[0], 'dealer_id')) {
        //                $sql = $sql->hasWhere('goods', function ($query) use ($v)
        //                {
        //                    $query->where($v[0], $v[1], $v[2]);
        //                });
        //                unset($where[$k]);
        //            }
        //        }
        $sql  = $sql->hasWhere('goods', function ($query) use (&$where)
        {
            $query->where('status', '=', 1);
            foreach ($where as $k => $v) {
                if (str_contains($v[0], 'cate_id')) {
                    if ($v[2] != 0) {
                        $query->where('dealer_cate_id', $v[1], $v[2]);
                    }
                    unset($where[$k]);
                }
                if (str_contains($v[0], 'dealer_id')) {
                    if ($v[2] != 0) {
                        $query->where($v[0], $v[1], $v[2]);
                    }
                    unset($where[$k]);
                }
                if (str_contains($v[0], 'goods_name')) {
                    $query->where('name', $v[1], $v[2]);
                    unset($where[$k]);
                }
            }
        });
        $list = $sql->where($where)->with('goods')->paginate($limit);

        $list = $list->each(function ($spec)
        {
            $goodsInfo = (new DealerGoods())->where('id', $spec->dealer_goods_id)->find();
            $stock     = 0;
            if ($spec->ratio != 0) $stock = bcdiv($goodsInfo->sales_stock, $spec->ratio);
            $spec->stock = $stock;
        });
        return $this->success($list);
    }

    /**
     * @NodeAnnotation(title="业务员列表")
     */
    public function salesmanList(): Json
    {
        $sql = $this->model = new Salesman();
        [$limit, $where] = $this->buildSearchParams();
        foreach ($where as $k => $v) {
            if (str_contains($v[0], 'dealer_id')) {
                $sql = $sql->hasWhere('dealer', function ($query) use ($v)
                {
                    $query->where($v[0], $v[1], $v[2]);
                });
                unset($where[$k]);
            }
        }
        $get = $this->request->get();
        if (empty($get['limit'])) {
            $list = $sql->where($where)->where('status', 1)->where('vk_salesman.company_id', $this->companyId)
                        ->order($this->sort)->select();
        } else {
            $list = $sql->where($where)->where('status', 1)->where('vk_salesman.company_id', $this->companyId)
                        ->order($this->sort)->paginate($limit);
        }
        return $this->success($list);
    }

    public function dealerCateList(): Json
    {
        $sql = $this->model = new DealerGoodsCate();
        [, $where] = $this->buildSearchParams();
        $list = $sql->field('id,pid,name')->where($where)->where('status', Status::NORMAL)->select();
        return $this->success((new CategoryService())->getTreeData($list));
    }

    /**
     * 仓库商品列表
     */
    public function warehouseGoodsList(): Json
    {
        // 查询中间表数据
        $sql   = $this->model = new CompanyWarehouseGoods();
        $where = [];
        if (!empty($this->get['warehouse_id'])) {
            $where[] = ['warehouse_id', '=', $this->get['warehouse_id']];
        }
        if (!empty($this->get['goods_id'])) {
            $where[] = ['dealer_goods_id', '=', $this->get['dealer_goods_id']];
        }
        if (!empty($this->get['goods_name'])) {
            $dealer_goods_ids = DealerGoodsModel::where('name', 'like', '%' . $this->get['goods_name'] . '%')
                                                ->column('id');
            $where[]          = ['dealer_goods_id', 'in', $dealer_goods_ids];
        }
        if (!empty($this->get['company_id'])) {
            $where[] = ['company_id', '=', $this->get['company_id']];
        }
        $sql = $sql->with([
                                  'goods' => function (Query $query)
                                  {
                                      $query->with('spec');
                                  }
                          ])
                   ->where($where)
                   ->order(['stock'=>'desc','id'=>'desc']);
        if (!empty($this->get['limit'])) {
            $list = $sql->paginate($this->get['limit']);
        } else {
            $list = $sql->select();
        }
        $data = [];
        $list = $list->each(function ($item) use (&$data)
        {
            if ($item->goods && $item->stock) {
                $data[] = $this->dealStock($item->goods, $item->stock);
            }
        })->toArray();
        if(!empty($this->get['limit'])){
            $list['data'] = $data;
        }else{
            $list = $data;
        }
        return $this->success($list);
    }

    public function dealStock($vo, $stock)
    {
        $data = $vo;
        $spec = $data->spec->toArray();
        usort($spec, function ($a, $b)
        {
            return $b['ratio'] <=> $a['ratio'];  // 使用太空船操作符进行升序排序
        });
        $warehouse_stock = $old_warehouse_stock = $stock;
        $warehouse_str   = '';
        $unit            = '';
        foreach ($spec as $value) {
            if (!$value['ratio']) continue;
            // 库内库存
            $warehouse_quotient = intdiv($warehouse_stock, $value['ratio']);
            $warehouse_stock    = $warehouse_stock % $value['ratio'];
            $warehouse_str      .= $warehouse_quotient . $value['unit'];
            if ($value['unit_type'] == 1) $unit = $value['unit'];
        }
        $vo->sales_stock = $warehouse_str . ' = ' . $old_warehouse_stock . $unit;
        $vo->warehouse_stock = $warehouse_str . ' = ' . $old_warehouse_stock . $unit;
        return $data;
    }

    /**
     * 业务员仓库列表
     */
    public function salesmanWarehouseList(): Json
    {
        $sql = $this->model = new CompanyWarehouse();
        $list = $sql->where(function ($query)
        {
            $query->where('company_id', $this->companyId)
                  ->where('type', 1)
                  ->where('status', 1);
        })->whereOr(function ($query)
        {
            $query->where('salesman_id', $this->uid)
                  ->where('type', 2)
                  ->where('status', 1);
        })->field('id,name,type')
                            ->select();
        return $this->success($list);
    }

}